from PyQt4 import QtCore, QtGui
from PyQt4.Qt import QFont
import os, dbus
from conf import Config

class ConfigGui(QtGui.QMainWindow):
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.setWindowTitle('LinRemote server configuration')
        self.setWindowIcon(QtGui.QIcon(os.getcwd()+'/tray.png'))
        self.w = QtGui.QWidget()
        self.setCentralWidget(self.w)
        
        self.f = QFont()
        self.f.setBold(True)
        
        self.logLabel = QtGui.QLabel('Logging settings:')
        self.logLabel.setFont(self.f)
        self.logFormatLabel = QtGui.QLabel('log message format:')
        self.logFormatLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.logFormatLineEdit = QtGui.QLineEdit()
        self.logFormatLineEdit.setFixedWidth(500)
        
        self.logFormatBox = QtGui.QHBoxLayout()
        self.logFormatBox.addWidget(self.logFormatLabel)
        self.logFormatBox.addWidget(self.logFormatLineEdit)
        self.logDateTimeFormatLabel = QtGui.QLabel('date and time format:')
        self.logDateTimeFormatLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.logDateTimeFormatLineEdit = QtGui.QLineEdit()
        self.logDateTimeFormatLineEdit.setFixedWidth(500)
        
        self.logDateTimeFormatBox = QtGui.QHBoxLayout()
        self.logDateTimeFormatBox.addWidget(self.logDateTimeFormatLabel)
        self.logDateTimeFormatBox.addWidget(self.logDateTimeFormatLineEdit)
        self.logLevelLabel = QtGui.QLabel('level:')
        self.logLevelLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.logLevelLineEdit = QtGui.QLineEdit()
        self.logLevelLineEdit.setFixedWidth(500)
        
        self.logLevelBox = QtGui.QHBoxLayout()
        self.logLevelBox.addWidget(self.logLevelLabel)
        self.logLevelBox.addWidget(self.logLevelLineEdit)
        self.logFileLabel = QtGui.QLabel('file:')
        self.logFileLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.logFileLineEdit = QtGui.QLineEdit()
        self.logFileLineEdit.setFixedWidth(500)
        
        self.logFileBox = QtGui.QHBoxLayout()
        self.logFileBox.addWidget(self.logFileLabel)
        self.logFileBox.addWidget(self.logFileLineEdit)
        self.logBox = QtGui.QVBoxLayout()
        self.logBox.addWidget(self.logLabel)
        self.logBox.addLayout(self.logFormatBox)
        self.logBox.addLayout(self.logDateTimeFormatBox)
        self.logBox.addLayout(self.logLevelBox)
        self.logBox.addLayout(self.logFileBox )
        
        self.socketLabel = QtGui.QLabel('Socket settings:')
        self.socketLabel.setFont(self.f)
        self.socketPortLabel = QtGui.QLabel('port:')
        self.socketPortLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.socketPortLineEdit = QtGui.QLineEdit()
        self.socketPortLineEdit.setFixedWidth(500)
        
        self.socketPortBox = QtGui.QHBoxLayout()
        self.socketPortBox.addWidget(self.socketPortLabel)
        self.socketPortBox.addWidget(self.socketPortLineEdit)
        self.socketHostLabel = QtGui.QLabel('hostname:')
        self.socketHostLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.socketHostLineEdit = QtGui.QLineEdit()
        self.socketHostLineEdit.setFixedWidth(500)
        
        self.socketHostBox = QtGui.QHBoxLayout()
        self.socketHostBox.addWidget(self.socketHostLabel)
        self.socketHostBox.addWidget(self.socketHostLineEdit)
        self.socketBufferSizeLabel = QtGui.QLabel('buffer size:')
        self.socketBufferSizeLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.socketBufferSizeLineEdit = QtGui.QLineEdit()
        self.socketBufferSizeLineEdit.setFixedWidth(500)
        
        self.socketBufferSizeBox = QtGui.QHBoxLayout()
        self.socketBufferSizeBox.addWidget(self.socketBufferSizeLabel)
        self.socketBufferSizeBox.addWidget(self.socketBufferSizeLineEdit)
        self.socketBox = QtGui.QVBoxLayout()
        self.socketBox.addWidget(self.socketLabel)
        self.socketBox.addLayout(self.socketPortBox)
        self.socketBox.addLayout(self.socketHostBox)
        self.socketBox.addLayout(self.socketBufferSizeBox)
        
        self.authLabel = QtGui.QLabel('*Authorization settings:')
        self.authLabel.setFont(self.f)
        self.authMethodLabel = QtGui.QLabel('method:')
        self.authMethodLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.authMethodLineEdit = QtGui.QLineEdit()
        self.authMethodLineEdit.setFixedWidth(500)
        
        self.authMethodBox = QtGui.QHBoxLayout()
        self.authMethodBox.addWidget(self.authMethodLabel)
        self.authMethodBox.addWidget(self.authMethodLineEdit)
        self.qrImgLabel = QtGui.QLabel('QR image location:')
        self.qrImgLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.qrImgLineEdit = QtGui.QLineEdit()
        self.qrImgLineEdit.setFixedWidth(500)
        
        self.qrImgBox = QtGui.QHBoxLayout()
        self.qrImgBox.addWidget(self.qrImgLabel)
        self.qrImgBox.addWidget(self.qrImgLineEdit)
        self.authBox = QtGui.QVBoxLayout()
        self.authBox.addWidget(self.authLabel)
        self.authBox.addLayout(self.authMethodBox)
        self.authBox.addLayout(self.qrImgBox)
        
        
        self.blacklistLabel = QtGui.QLabel('*Blacklist')
        self.blacklistLabel.setFont(self.f)
        self.blacklistIPLabel = QtGui.QLabel('IP list:')
        self.blacklistIPLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.blacklistIPLineEdit = QtGui.QLineEdit()
        self.blacklistIPLineEdit.setFixedWidth(500)
        
        self.blacklistIPBox = QtGui.QHBoxLayout()
        self.blacklistIPBox.addWidget(self.blacklistIPLabel)
        self.blacklistIPBox.addWidget(self.blacklistIPLineEdit)
        self.blacklistBox = QtGui.QVBoxLayout()
        self.blacklistBox.addWidget(self.blacklistLabel)
        self.blacklistBox.addLayout(self.blacklistIPBox)
        
        
        self.saveButton = QtGui.QPushButton(QtGui.QIcon.fromTheme('document-save'), '&Save')
        self.refreshButton = QtGui.QPushButton(QtGui.QIcon.fromTheme('view-refresh'),'&Refresh')
        self.applyButton = QtGui.QPushButton(QtGui.QIcon.fromTheme('dialog-ok-apply'), '&Save and Apply')
        
        self.buttons = QtGui.QHBoxLayout()
        self.buttons.addWidget(self.saveButton)
        self.buttons.addWidget(self.refreshButton)
        self.buttons.addWidget(self.applyButton)
        
        
        
        self.config = QtGui.QVBoxLayout()
        self.config.addLayout(self.logBox)
        self.config.addLayout(self.socketBox)
        self.config.addLayout(self.authBox)
        self.config.addLayout(self.blacklistBox)
        
        self.layout = QtGui.QVBoxLayout(self.w)
        self.layout.addLayout(self.config)
        self.layout.addLayout(self.buttons)
        
        QtCore.QObject.connect(self.authMethodLineEdit, QtCore.SIGNAL('textChanged(QString)'), self.authMethodChanged)
        QtCore.QObject.connect(self.saveButton, QtCore.SIGNAL('clicked()'), self.saveConfig)
        QtCore.QObject.connect(self.refreshButton, QtCore.SIGNAL('clicked()'), self.refreshConfig)
        QtCore.QObject.connect(self.applyButton, QtCore.SIGNAL('clicked()'), self.applyConfig)
        
        self.show()
        self.hide()
        
        self.setFixedSize(self.size())
        
        if Config.authMethod != 'qrcode':
            self.qrImgLineEdit.setDisabled(True)
        
    def showEvent(self, event):
        self.refreshConfig()
        event.ignore()
        
    def closeEvent(self, event):
        self.hide()
        event.ignore()
    
    def authMethodChanged(self):
        if self.authMethodLineEdit.text() == 'qrcode':
            self.qrImgLineEdit.setEnabled(True)
        else:
            self.qrImgLineEdit.setDisabled(True)

    def saveConfig(self):
        pwd = None
        try:
            bus = dbus.SessionBus()
            app = 'org.LinRemote.Server'
            path = '/org/LinRemote/Server'
            interface = 'org.LinRemote.Server'
            obj = bus.get_object(app, path)
            DBusInterface = dbus.Interface(obj, interface)
            pwd = getattr(DBusInterface, 'pwd')()
        except Exception:
            self.setWindowTitle('LinRemote server configuration. SERVER MIGHT NOT BE RUNNING!')
            return False
        if pwd != None:
            Config.load()
            self.setWindowTitle('LinRemote server configuration')
            config = Config.cfgData
            config['log']['format'] = self.logFormatLineEdit.text()
            config['log']['dateTimeFormat'] = self.logDateTimeFormatLineEdit.text()
            config['log']['level'] = self.logLevelLineEdit.text()
            config['log']['file'] = self.logFileLineEdit.text()
            config['socket']['host'] = self.socketHostLineEdit.text()
            config['socket']['port'] = self.socketPortLineEdit.text()
            config['socket']['bufferSize'] = self.socketBufferSizeLineEdit.text()
            config['blacklist']['IPlist'] = self.blacklistIPLineEdit.text()
            config['authorization']['method'] = self.authMethodLineEdit.text()
            config['authorization']['qrImg'] = self.qrImgLineEdit.text()
            
            
            with open(pwd + '/LinRemoteServer.cfg', 'w') as configfile:
                Config.cfgData.write(configfile)
    
    def applyConfig(self):
        self.saveConfig()
        try:
            bus = dbus.SessionBus()
            app = 'org.LinRemote.Server'
            path = '/org/LinRemote/Server'
            interface = 'org.LinRemote.Server'
            obj = bus.get_object(app, path)
            DBusInterface = dbus.Interface(obj, interface)
            getattr(DBusInterface, 'reloadCFG')()
            getattr(DBusInterface, 'reloadIgnoreList')()
        except Exception as msg:
            print(str(msg))
            return
    
    def refreshConfig(self):
        t = Config.load()
        self.logFormatLineEdit.setText(Config.logFormat)
        self.socketBufferSizeLineEdit.setText(str(Config.bufferSize))
        self.socketHostLineEdit.setText(Config.host)
        self.socketPortLineEdit.setText(str(Config.port))
        self.logFileLineEdit.setText(Config.logFile)
        self.logLevelLineEdit.setText(Config.logLevel)
        self.logDateTimeFormatLineEdit.setText(Config.logDateTimeFormat)
        self.authMethodLineEdit.setText(Config.authMethod)
        self.qrImgLineEdit.setText(Config.qrImg)
        self.blacklistIPLineEdit.setText(Config.blacklist)
        if t:
            self.setWindowTitle('LinRemote server configuration')
        else:
            self.setWindowTitle('LinRemote server configuration. SERVER MIGHT NOT BE RUNNING!')